package com.share.security;

import com.share.constant.JwtConstant;
import com.share.domain.CheckResult;
import com.share.domain.SysUser;
import com.share.exception.UserCountLockException;
import com.share.service.SysUserService;
import com.share.util.JwtUtils;
import com.share.util.StringUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * @program: java1234-admin3
 * 描述：  jwt鉴权过滤器，需要继承基本的鉴权过滤器 BasicAuthenticationFilter
 * @author: XLX
 * @create: 2022-11-14 23:23
 **/
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {


    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private MyUserDetailsServiceImpl myUserDetailsService;

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    private static final String URL_WHITELIST[] ={
            "/login",
            "/logout",
            "/captcha",
            "/password",
            "/static/**",
            "/test/**"

    } ;


    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }


    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("authorization");
        System.out.println("请求url:"+request.getRequestURI());
        //如果token是空  或者 url在白名单里，则放行
        if (StringUtil.isEmpty(token) || (new ArrayList<String>(Arrays.asList(URL_WHITELIST))).contains(request.getRequestURI())){
            System.out.println("放行");
            chain.doFilter(request,response);
            return;
        }
        CheckResult checkResult = JwtUtils.validateJWT(token);
        if (!checkResult.isSuccess()){
            switch (checkResult.getErrCode()){
                case JwtConstant.JWT_ERRCODE_EXPIRE: throw new UserCountLockException("token过期");
                case JwtConstant.JWT_ERRCODE_NULL: throw new UserCountLockException("token不存在");
                case JwtConstant.JWT_ERRCODE_FAIL: throw new UserCountLockException("验证不通过");
            }
        }

        Claims claims = JwtUtils.parseJWT(token);
        String username = claims.getSubject();
        SysUser sysUser = sysUserService.getByUsername(username);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser.getUsername(),sysUser.getPassword(),myUserDetailsService.getUserAuthority(sysUser.getId()));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        chain.doFilter(request,response);
    }
}